/*
 * @Author: humengchuan 531537052@qq.com
 * @Date: 2025-03-11 17:23:07
 * @LastEditors: humengchuan 531537052@qq.com
 * @LastEditTime: 2025-03-11 17:24:27
 * @FilePath: \project\work-tool\experi-api\utils\redisLock.js
 * @Description: redis分布式锁封装
 */
const redis = require('redis');

const redisClient = redis.createClient();

// 封装加锁逻辑
async function acquireLock(lockKey, lockValue, expirationInSeconds) {
    return new Promise((resolve, reject) => {
        redisClient.set(lockKey, lockValue, 'EX', expirationInSeconds, 'NX', (err, reply) => {
            if (err) return reject(err);
            if (reply === 'OK') resolve(true); // 成功获取锁
            else resolve(false); // 锁已被占用
        });
    });
}

// 封装释放锁逻辑（确保只有持有锁的客户端才能解锁）
async function releaseLock(lockKey, lockValue) {
    return new Promise((resolve, reject) => {
        redisClient.get(lockKey, (err, reply) => {
            if (err) return reject(err);
            if (reply === lockValue) {
                redisClient.del(lockKey, (error, res) => {
                    if (error) return reject(error);
                    resolve(res);
                });
            } else {
                resolve(0); // 不执行任何操作，因为锁不属于当前请求
            }
        });
    });
}

module.exports = { acquireLock, releaseLock }
// 示例路由，演示如何使用分布式锁
// app.get('/critical-section', async (req, res) => {
//     const lockKey = 'my-distributed-lock';
//     const lockValue = Date.now(); // 使用时间戳作为唯一标识符
//     const isLocked = await acquireLock(lockKey, lockValue, 10); // 设置10秒过期时间

//     if (isLocked) {
//         try {
//             // 执行关键业务逻辑
//             console.log('Processing critical section...');
//             res.send('Critical section processed.');
//         } finally {
//             // 确保在完成时释放锁
//             await releaseLock(lockKey, lockValue);
//         }
//     } else {
//         res.status(503).send('Resource temporarily unavailable due to lock.');
//     }
// });

